import 'package:flutter/material.dart';
import 'package:realmega_ota/constants.dart';
import 'package:realmega_ota/realmega/back_to_bottom_or_top_widget.dart';
import 'package:realmega_ota/realmega/back_to_top_widget.dart';
import 'package:realmega_ota/util/log_util.dart';
import 'package:realmega_ota/realmega/running_log_manager.dart';

class RunningLogWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    return _RunningLogState();
  }

}

class _RunningLogState extends State<RunningLogWidget> with AutomaticKeepAliveClientMixin{
  
  List<String> _logs = [];
  final ScrollController listviewController = ScrollController();
  bool inTouch = false;
  
  @override
  void initState() {
    super.initState();
    _logs = RunningLogManager.instance.getLogs();
    RunningLogManager.instance.runningLogs.listen((event) {
      if(!mounted){
        // Log.d('running log not mounted...');
        return;
      }
      // Log.d("runningLog:$event");
      _logs = event;
      setState(() {
        if(inTouch){
          return;
        }
        // listviewController.animateTo(listviewController.position.maxScrollExtent,
        //     duration: Duration(milliseconds: 200),
        //     curve: Curves.easeIn);
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    // RunningLogManager.instance.close();
  }
  
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Listener(child:SafeArea(
      ///这种场景，应该是要用stack的吧？要不然不会盖在页面上，布局问题就不多说了
        child: Stack(
            children: <Widget>[
              ListView.separated(
                  controller: listviewController,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      child: Text(_logs[index]),
                      margin: EdgeInsets.only(left: COMMON_MARGIN_LENGTH, right: COMMON_MARGIN_LENGTH),
                      padding: EdgeInsets.only(top: 20, bottom: 20),
                    );
                  },
                  separatorBuilder: (BuildContext context, int index) {
                    return const Divider(height: 1, indent: COMMON_MARGIN_LENGTH,);
                  },
                  itemCount: _logs.length
              ),
              ///返回顶部按钮，传入控制器
              BackToBottomOrTop(listviewController, bottom: 20,),
            ])),
      onPointerMove: (event){
        inTouch = true;
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}